//src/store/user.ts

import { FileHandle } from "@@/FileControl/openDirectory";
import { defineStore } from "pinia";
import { fileSave } from "browser-fs-access";
import mitt from "mitt";
interface State {
    treeData: any;
    handle?: FileHandle;
    isOpening: boolean;
}

const hub = mitt();
export { hub };
export const useStore = defineStore({
    id: "drawer", // id必填，且需要唯一
    state: (): State => {
        return {
            treeData: {},
            isOpening: false,
        };
    },
    actions: {
        async loadFile(fileHandle: FileHandle) {
            const data = await fileHandle.getFile();
            const text = await data.text();
            this.treeData = JSON.parse(text);
            this.handle = fileHandle;
            this.isOpening = true;
            hub.emit("openFile");
        },
        async writeFile(string: string) {
            if (!this.handle) {
                await this.createFile(string);
            } else {
                const writable = await this.handle!.createWritable<string>();
                // 通过管道将数据传输到文件
                await (writable as any).write(string);
                // 管道使用完毕后需要关闭
                await writable.close();
            }
            console.log("写入文件完成");
        },
        async createFile(string: string) {
            const handle = await fileSave(new Blob([string]), {
                fileName: "Untitled.json",
                extensions: [".json"],
            });
            this.handle = handle as any;
            console.log("创建文件成功");
        },
    },
});
